<script lang="ts" setup>
import { ref } from 'vue'
import { toNumber } from 'lodash-es'
import { ElMessage, ElTable } from 'element-plus'
import { Bottom, Top } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { GetApplyData, GetInviteData, GetStatisticsData, PostGenerateOrder, PostLotterystatus, PostSratusData } from '@/api/modules/freetrialapply'

const imgDomain = 'https://img1.eprhan.cc'
const router = useRouter()
const route = useRoute()
const TrialProductId = route.query.TrialProductId
const findFrom = ref({
  TrialProductId: (TrialProductId as string) ? TrialProductId : '',
  UserId: '',
  UserName: '',
  UserPhone: '',
  ApplyStatus: '~',
  LotteryStatus: '~',
  InviteConBase: '',
  UsedInviteConSortDesc: '',
})
const dataList: any = reactive({
  list: [],
  inviteList: [],
})
const loading = ref(true)
const total = ref(0)
let PageSize = 20
let PageNum = 1

const dialogTableVisible = ref(false)

const NumberWinners = ref(0)

async function GetDataList(PageIndex: number = 1, PageSize: number = 20) {
  const params = {
    PageIndex,
    PageSize,
    ...(findFrom.value.TrialProductId && ({ TrialProductId: findFrom.value.TrialProductId })),
    ...(findFrom.value.UserId && ({ UserId: findFrom.value.UserId })),
    ...(findFrom.value.UserName && ({ UserName: findFrom.value.UserName })),
    ...(findFrom.value.UserPhone && ({ UserPhone: findFrom.value.UserPhone })),
    ...((findFrom.value.ApplyStatus !== '' && findFrom.value.ApplyStatus !== '~') && ({ ApplyStatus: findFrom.value.ApplyStatus })),
    ...((findFrom.value.LotteryStatus !== '' && findFrom.value.LotteryStatus !== '~') && ({ LotteryStatus: findFrom.value.LotteryStatus })),
    ...(findFrom.value.InviteConBase && ({ InviteConBase: findFrom.value.InviteConBase })),
    ...(findFrom.value.UsedInviteConSortDesc !== '' && ({ UsedInviteConSortDesc: findFrom.value.UsedInviteConSortDesc })),
  }
  await GetApplyData(params).then(async (dataRes: any) => {
    if (dataRes.succeeded) {
      dataList.list = dataRes.data.items
      total.value = dataRes.data.total
      loading.value = false
    }
    else {
      ElMessage.error(`获取失败${dataRes.errors}`)
    }
  })
  loading.value = false
}

// 列表选中
let curDate = dayjs().format('YYYY-MM-DD HH:mm:ss')
// const selectable = (row: any) => row.lotteryTime < curDate && (row.lotteryStatus === -1 || row.lotteryStatus === 0)
// 存储id的数组
const multipleSelection = ref<any>([])
function handleSelectionChange(val: any) {
  multipleSelection.value = val
}
// 批量开奖
async function ModifyType() {
  if (multipleSelection.value.some((item: any) => {
    if (item.lotteryTime > curDate) {
      ElMessage.warning('未到开奖时间')
      return true
    }
    return false
  })) {
    return
  }
  const params = {
    idList: multipleSelection.value.map((item: any) => {
      return item.id
    }),
    isLuckyGuy: true,
    trialProductId: TrialProductId,
  }
  // console.log(params)
  await PostSratusData(params).then((res: any) => {
    if (res.statusCode === 200) {
      ElMessage.success('修改成功')
      GetDataList(PageNum, PageSize)
    }
    else {
      ElMessage.error(`修改失败${res.errors}`)
    }
  })
}

// 生成订单
function GenerateOrder() {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要修改的记录')
    return
  }
  if (multipleSelection.value.some((item: any) => {
    if (item.lotteryTime > curDate) {
      ElMessage.warning('未到开奖时间')
      return true
    }
    return false
  })) {
    return
  }
  if (multipleSelection.value.some((item: any) => {
    if (item.lotteryStatus !== 1 && item.lotteryStatus !== 2) {
      ElMessage.warning('只能修改已中奖和已评测的记录')
      return true
    }
    return false
  })) {
    return
  }
  if (multipleSelection.value.some((item: any) => {
    if (item.isGenerateOrder) {
      ElMessage.warning('已有记录生成订单')
      return true
    }
    return false
  })) {
    return
  }
  const params = {
    idList: multipleSelection.value.map((item: any) => {
      return item.id
    }),
  }
  PostGenerateOrder(params).then((res: any) => {
    if (res.statusCode === 200) {
      ElMessage.success('生成订单成功')
      GetDataList(PageNum, PageSize)
    }
    else {
      ElMessage.error(`生成订单失败${res.errors}`)
    }
  })
}

// 单条修改开奖状态
const dialogVisible = ref(false)
const LotterystatusData = ref<any>({})
function Lotterystatus(row: any) {
  curDate = dayjs().format('YYYY-MM-DD HH:mm:ss')
  LotterystatusData.value = { ...row }
  dialogVisible.value = true
}

function SetLotterystatusData() {
  const params = {
    id: LotterystatusData.value.id,
    Lotterystatus: LotterystatusData.value.lotteryStatus,
  }
  // console.log(params)
  PostLotterystatus(params).then((res: any) => {
    if (res.statusCode === 200) {
      ElMessage.success('修改成功')
      GetDataList(PageNum, PageSize)
    }
    else {
      ElMessage.error(`修改失败${res.errors}`)
    }
    dialogVisible.value = false
  })
}

// 查询
function Inquire() {
  GetDataList(1, PageSize)
}

// 邀请记录
let invitePageSize = 20
const inviteTotal = ref(0)
let TrialApplyId = 0
const inviteFrom = ref({
  UserId: '',
  NickName: '',
})
function GetInvite() {
  GetInviteList(1, PageSize, TrialApplyId)
}
function PagesNumber(val: number) {
  GetInviteList(1, val, TrialApplyId)
  invitePageSize = val
}
function BranchesNumber(val: number) {
  GetInviteList(val, PageSize, TrialApplyId)
}
async function GetInviteList(PageIndex: number = 1, PageSize: number = 20, TrialApplyId: number) {
  const params = {
    PageIndex,
    PageSize,
    TrialApplyId,
    ...(inviteFrom.value.UserId !== '' && ({ UserId: inviteFrom.value.UserId })),
    ...(inviteFrom.value.NickName !== '' && ({ NickName: inviteFrom.value.NickName })),
  }
  await GetInviteData(params).then(async (dataRes: any) => {
    if (dataRes.succeeded) {
      dataList.inviteList = dataRes.data.items
      inviteTotal.value = dataRes.data.total
    }
  })
}
async function freetrialInvite(isTrialApplyId: number) {
  // router.push({
  //   name: 'freetrialInvite',
  //   query: {
  //     TrialApplyId,
  //   },
  // })
  dialogTableVisible.value = true
  TrialApplyId = isTrialApplyId
  GetInviteList(1, invitePageSize, isTrialApplyId)
}
// 评测记录
function freetrialevaluation(TrialApplyId: string) {
  router.push({
    name: 'freetrialevaluation',
    query: {
      TrialApplyId,
    },
  })
}

// 排序
function Sort(column: any) {
  if (column.label === '邀请数量') {
    if (findFrom.value.UsedInviteConSortDesc !== '') {
      (findFrom.value.UsedInviteConSortDesc as string | boolean) = !findFrom.value.UsedInviteConSortDesc
    }
    else {
      (findFrom.value.UsedInviteConSortDesc as string | boolean) = true
    }
    GetDataList(1, PageSize)
  }
}

// 翻页
function handleSizeChange(val: number) {
  GetDataList(1, val)
  PageSize = val
}
function handleCurrentChange(val: number) {
  GetDataList(val, PageSize)
  PageNum = val
}

const nowPageNum = computed(() => {
  return toNumber(localStorage.getItem('currentPage')) || 1
})

onMounted(() => {
  GetDataList()
  if ((TrialProductId as string) !== undefined) {
    GetStatisticsData({ trialproductid: TrialProductId }).then((res: any) => {
      if (res.succeeded) {
        NumberWinners.value = res.data.currentWinners
      }
    })
  }
})
</script>

<template>
  <div>
    <PageMain>
      <SearchBar :show-toggle="false">
        <div class="header">
          <el-form label-positio="right" label-width="auto">
            <div class="from">
              <el-form-item label="试用商品ID">
                <el-input v-model="(findFrom.TrialProductId as string)" :disabled="(TrialProductId as string) !== undefined" style="width: 300px;" placeholder="请输入试用商品ID" @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="用户ID">
                <el-input v-model="findFrom.UserId" style="width: 300px;" placeholder="请输入用户ID" @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="姓名">
                <el-input v-model="findFrom.UserName" style="width: 300px;" placeholder="请输入姓名" @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="手机号">
                <el-input v-model="findFrom.UserPhone" style="width: 300px;" placeholder="请输入手机号" @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="申请状态">
                <el-select v-model="findFrom.ApplyStatus" placeholder="请选择申请状态" style="width: 300px;" clearable>
                  <el-option label="全部" value="~" />
                  <el-option label="未加企微" :value="0" />
                  <el-option label="正常" :value="1" />
                </el-select>
              </el-form-item>
              <el-form-item label="开奖状态">
                <el-select v-model="findFrom.LotteryStatus" placeholder="请选择开奖状态" style="width: 300px;" clearable>
                  <el-option label="全部" value="~" />
                  <el-option label="未开奖" :value="-1" />
                  <el-option label="未中奖" :value="0" />
                  <el-option label="已中奖" :value="1" />
                  <el-option label="已评测" :value="2" />
                </el-select>
              </el-form-item>
              <el-form-item label="最少邀请数量">
                <el-input v-model="findFrom.InviteConBase" style="width: 300px;" placeholder="请输入最少邀请数量" @keyup.enter="Inquire" />
              </el-form-item>
              <!-- <el-form-item label="邀请数量排序">
                <el-select v-model="findFrom.UsedInviteConSortDesc" placeholder="请选择邀请数量排序" style="width: 300px;">
                  <el-option label="默认" value="" />
                  <el-option label="倒序" :value="true" />
                  <el-option label="升序" :value="false" />
                </el-select>
              </el-form-item> -->
            </div>
          </el-form>
          <div class="text-right">
            <el-button @click="Inquire">
              查询
            </el-button>
          </div>
        </div>
      </SearchBar>
      <ElDivider border-style="dashed" />
      <!-- <div v-if="(TrialProductId as string) !== undefined">
        ces
      </div> -->
      <div class="mb-5">
        <el-button v-if="(TrialProductId as string) !== undefined" @click="ModifyType">
          更改中奖状态
        </el-button>
        <el-button @click="GenerateOrder">
          批量生成订单
        </el-button>
        <span v-if="(TrialProductId as string) !== undefined" style="color: #909399;">
          中奖人数：{{ NumberWinners }}
        </span>
      </div>
      <ElTable v-loading="loading" :data="dataList.list" stripe style="width: 100%;" border row-key="id" @selection-change="handleSelectionChange" @header-click="Sort">
        <el-table-column type="selection" width="55" align="center" fixed="left" reserve-selection />
        <el-table-column align="center" prop="id" label="ID" width="100" />
        <el-table-column align="center" prop="trialProductInfo.id" label="0元试用ID" width="100" />
        <el-table-column align="center" prop="trialProductInfo.title" label="标题" width="300" show-overflow-tooltip />
        <el-table-column align="center" label="封面图" width="120">
          <template #default="scope">
            <el-avatar shape="square" :size="60" :src="imgDomain + scope.row.trialProductInfo?.proImg" />
          </template>
        </el-table-column>
        <el-table-column align="center" prop="productInfo.productId" label="试用商品ID" width="100" />
        <el-table-column header-align="center" prop="productInfo.productName" label="试用商品名称" width="400" show-overflow-tooltip />
        <el-table-column align="center" prop="productInfo" label="试用商品类型" width="140">
          <template #default="scope">
            <el-tag type="primary">
              {{ scope.row.productInfo?.flag === 1 ? '正常商品'
                : scope.row.productInfo?.flag === 2 ? '积分商品'
                  : scope.row.productInfo?.flag === 3 ? '秒杀商品' : '未定义' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="CDN商品封面" width="120">
          <template #default="scope">
            <el-avatar shape="square" :size="60" :src="imgDomain + scope.row.productInfo?.cdnProductPhotoPic" />
          </template>
        </el-table-column>
        <el-table-column align="center" prop="subscriberInfo.userId" label="用户ID" width="100" />
        <el-table-column align="center" prop="subscriberInfo.scOpenId" label="OpenID" width="280" />
        <el-table-column align="center" prop="subscriberInfo" label="用户信息" width="200">
          <template #default="scope">
            <div v-if="!scope.row.subscriberInfo">
              未授权
            </div>
            <div v-else class="user-name">
              <el-avatar :size="40" style="margin-right: 10px;" :src="scope.row.subscriberInfo?.userAvatar" />
              <div>
                <p style="margin: 0;">
                  {{ scope.row.subscriberInfo?.userNickName }}
                </p>
                <span>
                  {{ scope.row.subscriberInfo?.userPhone }}
                </span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="userName" label="姓名" width="200" />
        <el-table-column align="center" prop="userPhone" label="手机号" width="200" />
        <el-table-column align="center" label="地区" width="200">
          <template #default="scope">
            <span>
              {{ scope.row.province }}-{{ scope.row.city }}-{{ scope.row.area }}
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="address" label="详细地址" width="240" />
        <el-table-column align="center" prop="applyStatus" label="申请状态" width="100">
          <template #default="scope">
            <el-tag type="primary">
              {{ scope.row.applyStatus === 0 ? '未加企微'
                : scope.row.applyStatus === 1 ? '正常' : '未定义' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="desp" label="备注" width="200" />
        <el-table-column align="center" prop="lotteryTime" label="开奖时间" width="200" />
        <el-table-column align="center" prop="addTime" label="申请时间" width="200" />
        <el-table-column align="center" prop="updateTime" label="修改时间" width="200" />
        <el-table-column align="center" prop="lotteryStatus" label="开奖状态" fixed="right" width="90">
          <template #default="scope">
            <el-tag type="primary">
              {{ scope.row.lotteryStatus === -1 ? '未开奖'
                : scope.row.lotteryStatus === 0 ? '未中奖'
                  : scope.row.lotteryStatus === 1 ? '已中奖'
                    : scope.row.lotteryStatus === 2 ? '已评测' : '未定义' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="lotteryStatus" label="会员信息" fixed="right" width="150">
          <template #default="scope">
            <span>
              {{ scope.row.levelInfo?.vipLevel }} - {{ scope.row.levelInfo?.vipName }}
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="lotteryStatus" label="生成订单状态" fixed="right" width="109">
          <template #default="scope">
            <span v-if="!(scope.row.lotteryStatus === 1 || scope.row.lotteryStatus === 2)">
              无
            </span>
            <span v-else type="primary">
              {{ scope.row.isGenerateOrder ? '已生成订单' : '未生成订单' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="historyWinPrizeCon" label="历史中奖次数" width="109" fixed="right" />
        <el-table-column align="center" prop="inviteCon" label="邀请数量" width="110" fixed="right">
          <template #header>
            <span style=" width: 100%; height: 100%;cursor: pointer;">
              邀请数量
              <el-icon v-if="findFrom.UsedInviteConSortDesc"><Top /></el-icon>
              <el-icon v-if="!findFrom.UsedInviteConSortDesc"><Bottom /></el-icon>
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" fixed="right" width="280">
          <template #default="scope">
            <div class="button-box">
              <el-button @click="freetrialInvite(scope.row.id)">
                查看邀请记录
              </el-button>
              <el-button @click="freetrialevaluation(scope.row.id)">
                查看评测记录
              </el-button>
              <el-button type="primary" @click="Lotterystatus(scope.row)">
                修改开奖状态
              </el-button>
            </div>
          </template>
        </el-table-column>
      </ElTable>
      <div style="height: 10px;" />
      <el-pagination
        :default-page-size="20"
        :page-sizes="[5, 10, 20, 50, 100]"
        layout="total, sizes, ->, prev, pager, next, jumper"
        :total="total"
        :default-current-page="nowPageNum"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </PageMain>
    <el-dialog v-model="dialogTableVisible" title="邀请记录" width="1600">
      <SearchBar :show-toggle="false">
        <div class="header" style="margin-bottom: 10px;">
          <el-form label-positio="right" label-width="auto">
            <div class="from">
              <el-form-item label="用户ID">
                <el-input v-model="inviteFrom.UserId" style="width: 300px;" placeholder="请输入用户ID" @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="昵称">
                <el-input v-model="inviteFrom.NickName" style="width: 300px;" placeholder="请输入昵称" @keyup.enter="Inquire" />
              </el-form-item>
            </div>
          </el-form>
          <div class="text-right">
            <el-button @click="GetInvite">
              查询
            </el-button>
          </div>
        </div>
      </SearchBar>
      <ElTable v-loading="loading" :data="dataList.inviteList" stripe style="width: 100%;" border>
        <el-table-column align="center" prop="id" label="ID" width="100" />
        <el-table-column align="center" prop="trialApplyId" label="试用品申请ID" width="200" />
        <el-table-column align="center" prop="subscriberInfo.userId" label="用户ID" width="200" />
        <el-table-column align="center" prop="subscriberInfo.scOpenId" label="OpenID" width="200" />
        <el-table-column align="center" prop="subscriberInfo" label="用户信息" width="200">
          <template #default="scope">
            <div v-if="!scope.row.subscriberInfo">
              未授权
            </div>
            <div v-else class="user-name">
              <el-avatar :size="40" style="margin-right: 10px;" :src="scope.row.subscriberInfo?.userAvatar" />
              <div>
                <p style="margin: 0;">
                  {{ scope.row.subscriberInfo?.userNickName }}
                </p>
                <span>
                  {{ scope.row.subscriberInfo?.userPhone }}
                </span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="nickName" label="昵称" width="200" />
        <el-table-column align="center" label="头像" width="200">
          <template #default="scope">
            <ElImage style=" width: auto;height: 60px;" :src="scope.row.avatar" />
          </template>
        </el-table-column>
        <el-table-column align="center" prop="recStatus" label="状态" width="200">
          <template #default="scope">
            <el-tag type="primary">
              {{ scope.row.recStatus === 1 ? '已助力' : '未定义' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="addTime" label="添加时间" width="200" />
        <el-table-column align="center" prop="updateTime" label="修改时间" width="200" />
      </ElTable>
      <div style="height: 10px;" />
      <el-pagination
        :default-page-size="20"
        :page-sizes="[5, 10, 20, 50, 100]"
        layout="total, sizes, ->, prev, pager, next, jumper"
        :total="inviteTotal"
        @size-change="PagesNumber"
        @current-change="BranchesNumber"
      />
    </el-dialog>
    <el-dialog
      v-model="dialogVisible"
      title="开奖状态"
      width="500"
    >
      <el-radio-group v-model="LotterystatusData.lotteryStatus">
        <el-radio :value="-1" :disabled="curDate > LotterystatusData.lotteryTime || LotterystatusData.isGenerateOrder">
          未开奖
        </el-radio>
        <el-radio :value="0" :disabled="(curDate < LotterystatusData.lotteryTime) || LotterystatusData.isGenerateOrder">
          未中奖
        </el-radio>
        <el-radio :value="1" :disabled="(curDate < LotterystatusData.lotteryTime) || LotterystatusData.isGenerateOrder">
          已中奖
        </el-radio>
        <el-radio :value="2" :disabled="curDate < LotterystatusData.lotteryTime">
          已评测
        </el-radio>
      </el-radio-group>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="SetLotterystatusData">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.header {
  display: grid;
  grid-template-columns: 6fr 1fr;

  .from {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    grid-gap: 20px;

    .el-form-item {
      margin-bottom: 0;
    }
  }
}

.user-name {
  display: flex;
  align-items: center;
  justify-content: left;

  div {
    text-align: left;
  }
}

.button-box {
  line-height: 42px;
}
</style>
